<template>
    <!-- 创建人所属分公司与分公司级下所有项目部 -->
    <div class="ProjectDepTree-container">
        <a-tree-select
            :tree-data="treeData"
            style="width: 100%"
            :replaceFields="replaceFields"
            v-on="$listeners"
            v-bind="$attrs"
            :value="modelValue"
            @change="handleTreeSelectChanged"
            :dropdownStyle="{
          maxHeight: '400px'
      }"
        />
    </div>
</template>

<script>
import { getCurrentUserBranchCom } from '@/api/themeChoose/themeChoose'
import { getProjectsList } from '@/api/projects'

export default {
    model: {
        prop: 'modelValue',
        event: 'modelChange'
    },
    props: {
        modelValue: {
            type: [String, Number],
            default: ''
        },
        showProject: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            treeData: [],
            replaceFields: {
                title: 'name',
                children: 'children'
            }
        }
    },
    created() {
        this.getCurrentUserBranchCom()
    },
    methods: {
        async getProjectsList(id, data) {
            try {
                const params = {
                    branchComId: id,
                    pageNo: 1,
                    pageSize: 99999
                }
                const res = await getProjectsList(params)
                if (res.code === 200) {
                    const list = (res.data || []).map(item => {
                        return {
                            ...item,
                            name: item.projectName,
                            key: item.projectId,
                            value: item.projectId
                        }
                    })
                    data.children = list
                }
            } catch {
            }
        },
          getCurrentUserBranchCom() {
            getCurrentUserBranchCom().then(res => {
                if (res.code === 200) {
                    this.treeData = (res.data || []).map(item => {
                        const result = {
                            ...item,
                            id: item.orgId,
                            key: item.orgId,
                            value: item.orgId,
                            name: item.orgName,
                            children: []
                        }
                        this.showProject && this.getProjectsList(result.id, result)
                        return result
                    })
                    this.$console(this.treeData)
                    this.$console(this.modelValue)
                }
            })
        },
        handleTreeSelectChanged(val, label, extra) {
            this.$emit('modelChange', val)
            this.$emit('modelChangeLabel', label)
        }
    }
}
</script>

<style>
</style>